package com.example.proxy.http;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class WebClient {


    /**
     * 通过get来访问url
     *
     * @param src 需要访问的url
     * @return
     * @throws Exception
     */
    public static String doGet(String src, Map<String, String> map) throws Exception {
        if (map != null) {
            src += "?";
            int i = 0;
            for (String key : map.keySet()) {
                if (i == 0) {
                    src += key + "=" + map.get(key);
                } else {
                    src += "&" + key + "=" + map.get(key);
                }
                i++;
            }
        }
        return doGet(src, "utf-8");
    }

    public static String doGet(String src) throws Exception {
        return doGet(src, Collections.emptyMap());
    }

    /**
     * 通过get来访问url
     *
     * @param src          需要访问的地址
     * @param outputencode 获取输出时的编码
     * @return
     * @throws Exception
     */
    public static String doGet(String src, String outputencode) throws Exception {
        return doGet(src, outputencode, null);
    }

    /**
     * 通过get来访问url
     *
     * @param src          需要访问的地址
     * @param outputencode 获取输出时的编码
     * @param headers      需要添加的访问头信息
     * @return
     * @throws Exception
     */
    public static String doGet(String src, String outputencode, HashMap<String, String> headers) throws Exception {
        StringBuilder result = new StringBuilder();
        URL url = new URL(src);
        URLConnection connection = url.openConnection();
        BufferedReader in = null;
        try {
            if (headers != null) {
                Iterator<String> iterators = headers.keySet().iterator();
                while (iterators.hasNext()) {
                    String key = iterators.next();
                    connection.setRequestProperty(key, headers.get(key));
                }
            }
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), outputencode));
            String line;
            while ((line = in.readLine()) != null) {
                result.append("\n" + line);
            }
            return result.toString();
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (in != null) {
                in.close();
            }
        }

    }


    /**
     * 向指定URL发送POST方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是name1=value1&name2=value2的形式。
     * @return URL所代表远程资源的响应
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "UTF-8");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStream outputStream = conn.getOutputStream();

            // 注意编码格式
            outputStream.write(param.getBytes("UTF-8"));
            outputStream.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += "/n" + line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


}
